<?php

namespace app\admin\controller\goods;

use app\admin\library\Auth;
use app\common\controller\Backend;
use app\common\model\coll\Analysis;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\Storehouse;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use app\common\model\purchase\Goods as Gmodel;
use app\common\model\sales\Goods as smodel;
use app\common\model\goods\Cate;
use app\common\model\goods\GoodsHouseStock as stock;
use app\common\model\supplier\Supplier;
use app\common\model\supplier\Brands;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Exception;
use think\exception\PDOException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\common\model\goods\Cate as CateModel;
use function fast\e;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
    
    /**
     * Goods模型对象
     * @var \app\common\model\goods\Goods
     */
    protected $model = null;
    protected $searchFields = 'id,title,specs,number';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\goods\Goods;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("materialList", $this->model->getMaterialList());
//        $Gmodel = new Gmodel;
//        $types= $Gmodel->goods_type();
//        $this->assignconfig('types',$types);
        $Storehouse = new Storehouse;
        $hlist = $Storehouse->select();
        $hslist = [];
        foreach ($hlist as $value){
            $hslist[$value['id']] = $value['name'];
        }
        $this->assignconfig('hslist',$hslist);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
//                dump(input());
                $title = input('title');
                $where['title'] = array('like','%'.$title.'%');
                $where['number'] = array('like','%'.$title.'%');
                $list = Db::name('goods')
                    ->field('id,title,number')
                    ->whereOr('title','like','%'.$title.'%')
                    ->whereOr('number','like','%'.$title.'%')
                    ->page(input('pageNumber'),input('pageSize'))
                    ->select();
                $total = Db::name('goods')
                    ->whereOr('title','like','%'.$title.'%')
                    ->whereOr('number','like','%'.$title.'%')
                    ->page(input('pageNumber'),input('pageSize'))
                    ->count();
                foreach ($list as &$v){
                    $v['title'] = $v['title'].$v['number'];
                    $v['pid'] =0;
                    unset($v['number']);
                }
                return array(
                    'list'=>$list,
                    'total'=>$total,
                );
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['cate','supplier','brands'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['cate','supplier','brands'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','title','place_origin','number','is_material','unit','createtime','status','price','specs','stock','new_cost_price','weigh','sync_status']);
                $row->visible(['cate']);
				$row->getRelation('cate')->visible(['name']);
				$row->visible(['supplier']);
				$row->getRelation('supplier')->visible(['nickname']);
                $row->visible(['brands']);
                $row->getRelation('brands')->visible(['name']);
            }

            $list = collection($list)->toArray();
            $stock = new stock;
            $syncstatus = array(
              1=>'及时更新',
              2=>'定时更新',
              3=>'不更新',
            );
            foreach ($list as $k=>  $v){
                $list[$k]['stock'] = $stock->getstock($v['id'],session('admin')['storehouse_id']);
                $list[$k]['sync_status'] = $syncstatus[$v['sync_status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function addpgoods($ids = null){
        $house = new Storehouse();
        $hwhere = [];
        if(!empty(session('admin')['storehouse_id'])){
            $hwhere['id'] = session('admin')['storehouse_id'];
        }
        $hrows = $house->where($hwhere)->select();
        $this->assign('hrows',$hrows);
        if ($this->request->isAjax())
        {

            $params = input();
            $grows = Db::name('goods')->where(array('id'=>$params['row']['goods_id']))->find();
            if($grows['status'] == 'hidden'){
                $this->error('该商品已下架');
            }
            if(empty($params['row']['goods_num']) || $params['row']['goods_num'] <=0 || empty($params['row']['goods_id']) || empty($params['row']['storehouse_id'])){
                $this->error('参数异常');
            }
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
            $data = array(
                'goods_id'=>$params['row']['goods_id'],
                'goods_num'=>$params['row']['goods_num'],
                'storehouse_id'=>$params['row']['storehouse_id'],
                'needtime'=>empty($params['row']['needtime'])?time():strtotime($params['row']['needtime']),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
            );
            $Gmodel = new Gmodel;
            $Gmodel->save($data);
            if($Gmodel->id){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
            exit;
        }
        $row = Db::name('goods')
            ->alias('g')
            ->field('g.id,c.name,s.nickname,title,place_origin,unit,price,specs,g.number')
            ->where(array('g.id'=>$ids))
            ->join('goods_cate c','g.cate_id = c.id','LEFT')
            ->join('supplier s','g.supplier_id = s.id','LEFT')
            ->find();

        $stock = new stock;
        $row['stock'] = $stock->getstock($row['id'],session('admin')['storehouse_id']);
        $this->assign('row',$row);
        $this->assign('gid',$ids);
        return $this->view->fetch();
    }

    public function specs(){
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $where=[];
            $filter = input('filter');
            $filter = json_decode($filter,true);
            $order = input('order');
            $offset = input('offset');
            $sort = input('sort');
            $sort = empty($sort)?'g.weigh':$sort;
            if($sort =='stock'){
                $where['s.stock'] = array('>',0);
            }
            $limit = input('limit');

            $search = input('search');
            if(!empty($search)){
                $where['id|title|specs'] = array('like','%'.$search.'%');
//                $where['specs'] = array('like','%'.$search.'%');
            }
            if($filter){
                foreach ($filter as  $key => $value){
                    if($key == 'supplier_id' && !empty($value)){
                        $where[$key] = $value;
                    }
                    if($key == 'storehouse_id'){
                        $storehouse_id = $value;
                    }
                    if($key == 'number'){
                        $where['number'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'specs'){
                        $where['specs'] = array('like','%'.$value.'%');
                    }
                    if($key == 'place_origin'){
                        $where['place_origin'] = array('like','%'.$value.'%');
                    }
                    if($key == 'brands_id'){
                        $where['brands_id'] = $value;
                    }
                    if($key == 'is_material'){
                        $where['is_material'] = $value;
                    }
                    if($key == 'title'){
                        $where['title'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'cate_id'){
                        $where['cate_id'] = $value;
                    }
                    if($key == 'is_stock'){
                        $where['s.stock'] = array('>',0);
                    }
                }
            }

            if(isset($where['s.stock'])){
                $where['storehouse_id'] = $storehouse_id;
                $list = Db::name('goods')
                    ->field('g.id,title,place_origin,number,specs,createtime,stock')
                    ->alias('g')
                    ->join('goods_house_stock s','g.id = s.goods_id')
                    ->where($where)
                    ->limit($offset,$limit)
                    ->order($sort,$order)
                    ->select();
                $total = Db::name('goods')
                    ->alias('g')
                    ->join('goods_house_stock s','g.id = s.goods_id')
                    ->where($where)
                    ->count();
            }else{
//                $where['s.storehouse_id'] = $storehouse_id;
                $list = Db::name('goods')
                    ->field('g.id,title,place_origin,number,specs,createtime')
                    ->alias('g')
//                    ->join('goods_house_stock s','g.id = s.goods_id','LEFT')
                    ->where($where)
                    ->limit($offset,$limit)
                    ->order($sort,$order)
                    ->select();
//                dump(Db::name('goods')->getLastSql());
//                exit;
                $total = Db::name('goods')
                    ->alias('g')
//                    ->join('goods_house_stock s','g.id = s.goods_id','LEFT')
                    ->where($where)
                    ->count();
            }



            $stock = new stock;
            foreach ($list as $k=>  $v){
                $list[$k]['stock'] = $stock->getstock($v['id'],$filter['storehouse_id']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function getinfo(){
        $sid = input('sid/d',0);
        $row = Db::name('goods')
            ->where(array('id'=>$sid))
            ->find();
        if($row){
            return $row;
        }
        return null;
    }


    //编号规则重定义
    public function add(){
        if ($this->request->isAjax()) {

            $params = input('');

//            $cate_id = input('cate_id');
//            if(empty($cate_id)){
//                $this->error('分类不能为空');
//            }
            $data = $params['row'];

            if(empty($data['number'])){
                //随机编码
                $number = generateRandomString(10);
                $data['number'] = $number;
//                $cate = new Cate();
//                $cnumber = $cate->catenumber($params['cate_id']);
//                $row = $this->model->where(array('id'=>array('>',99999),'cate_id'=>$cate_id))->order('number','DESC')->find();
//                if(empty($row)){
//                    $data['number'] = $this->getnum('1'.$cnumber.getnumber(0));
//                }else{
//                    $data['number'] = intval($row['number'])+1;
//                    $rrr = $this->model->where(array('number'=>$data['number']))->find();
//                    if($rrr){
//                        $data['number'] = intval($data['number'])+1;
//                    }
//                }
            }

//            $data['cate_id'] = $cate_id;
            $res = $this->model->save($data);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
            exit;
        }
        $tree = Tree::instance();
        $tree->init(collection(CateModel::order('weigh desc,id desc')->select())->toArray(), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $typeList = CateModel::getTypeList();
        $this->view->assign("typeList", $typeList);
        $this->view->assign("parentList", $categorydata);
        return $this->view->fetch();
    }
    public function getnum($num){
        $rr =Db::name('goods')->where(array('number'=>$num))->find();
        if($rr){
            $number = intval($rr['number'])+1;
            return $this->getnum($number);
        }
        return $num;
    }
    public function edit($ids = null){
        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $params = input('');

            if(!empty($params['row']['supplier_id'])){
                $supplier = new Supplier();
                $sinfo = $supplier->find($params['row']['supplier_id']);
                if(empty($sinfo)){
                    $this->error('数据异常');
                }
            }

            $brand = new Brands();
            $binfo = $brand->find($params['row']['brands_id']);
            if(empty($binfo)){
                $this->error('数据异常');
            }
            if (empty($params['row']['number'])){
                $params['row']['number'] = $row['number'];
            }else{
                $res =    $this->model->where(['number'=>$params['row']['number']])->find($ids);
                if ($res){
                    $this->error('编号已存在');
                }
            }

//            $number = $cnumber.getnumber($sinfo['id']).$binfo['number'];
            $data = $params['row'];
            $res = $this->model->save($data,array('id'=>$ids));
            if($res){
                $this->success('修改成功');
            }else{
                $this->error('添加失败');
            }
            exit;
        }


        $this->assign('row',$row);

        $tree = Tree::instance();
        $tree->init(collection(CateModel::order('weigh desc,id desc')->select())->toArray(), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $typeList = CateModel::getTypeList();
        $this->view->assign("typeList", $typeList);
        $this->view->assign("parentList", $categorydata);
        return $this->view->fetch();
    }
    public function lists($ids){
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);
            $where = [];
            $where['g.id'] = $ids;
            if(session('admin')['storehouse_id'] >0){
                $where['ss.storehouse_id'] = session('admin')['storehouse_id'];
            }

            if(!empty($filter)){
                foreach ($filter as $key =>$value){
                    if($key == 'type'){
                        $where['type'] = $value;
                    }
                    if($key == 'id'){
                        $where['pg.id'] = $value;
                    }
                    if($key == 'status'){
                        $where['pg.status'] = $value;
                    }
                    if($key == 'goods_num'){
                        $where['goods_num'] = $value;
                    }
                    if($key == 'name'){
                        $where2['name'] = $value;
                        $info = Storehouse::where($where2)->find();
                        $where['pg.storehouse_id'] = $info['id'];
                    }
                }
            }

            $sort = input('sort');
            $order = input('order');
            $offset = input('offset');
            $limit = input('limit');

            $list = Db::name('purchase_goods')
                ->field('pg.id,title,place_origin,unit,pg.status,pg.unit_price,type,name,pg.goods_num,eg.final_cost')
                ->alias('pg')
                ->join('goods g',' pg.goods_id = g.id ')
                ->join('storehouse h','pg.storehouse_id = h.id')
                ->join('purchase_enter_goods eg','pg.id = eg.purchase_goods_id')
                ->where($where)
                ->order('pg.id', $order)
                ->limit($offset, $limit)
                ->select();

            $mgoods = new Gmodel;
            $states = $mgoods->goods_status();
            $typess = $mgoods->goods_type();
            foreach ($list as $k=>$v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $states[$v['status']];
                $list[$k]['ytype'] = $v['type'];
                $list[$k]['type'] = $typess[$v['type']];
            }
            $total = Db::name('goods')
                ->alias('g')
                ->join('purchase_goods pg','g.id = pg.goods_id')
                ->join('storehouse h','pg.storehouse_id = h.id')
                ->join('purchase_enter_goods eg','pg.id = eg.purchase_goods_id')
                ->where($where)
                ->count();
            return  array(
              'rows'=>$list,
              'total'=>$total,
            );
        }

        return $this->view->fetch();
    }

    public function addgoodslog($ids){
//        purchase_goods   goods_house_stock
        $row = $this->model->find($ids);

        if ($this->request->isAjax())
        {
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $params = input('row/a');
            $data = array(
               'goods_id'=>$ids,
//               'supplier_id'=>$params['supplier_id'],
               'storehouse_id'=>$params['storehouse_id'],
               'goods_num'=>$params['goods_num'],
               'remark'=>$params['remark'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'type'=>2,
            );
            $purchase = new  Gmodel;
            $res = $purchase->save($data);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }

        $this->assign('row',$row);
        $house = new Storehouse();
        $hwhere = [];
        if(!empty(session('admin')['storehouse_id'])){
            $hwhere['id'] = session('admin')['storehouse_id'];
        }
        $hrows = $house->where($hwhere)->select();
        $this->assign('hrows',$hrows);
        return $this->view->fetch();
    }
    public function addsalelog($ids){
//        purchase_goods   goods_house_stock
        $row = $this->model->find($ids);

        if ($this->request->isAjax())
        {
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $params = input('row/a');
            $data = array(
               'goods_id'=>$ids,
//               'supplier_id'=>$params['supplier_id'],
               'storehouse_id'=>$params['storehouse_id'],
               'goods_num'=>$params['goods_num'],
               'remark'=>$params['remark'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'type'=>2,
                'createtime'=>time(),
            );
            $res =Db::name('sales_goods')->insert($data);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }


        $this->assign('row',$row);
        $house = new Storehouse();
        $hwhere = [];
        if(!empty(session('admin')['storehouse_id'])){
            $hwhere['id'] = session('admin')['storehouse_id'];
        }
        $hrows = $house->where($hwhere)->select();
        $this->assign('hrows',$hrows);
        return $this->view->fetch();
    }
    //销售记录
    public function plists($ids){
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);

            $where['g.id'] = $ids;
            if(!empty($filter)){

                foreach ($filter as $key =>$value){
                    if($key == 'type'){
                        $where['type'] = $value;
                    }
                    if($key == 'id'){
                        $where['pg.id'] = $value;
                    }
                    if($key == 'status'){
                        $where['pg.status'] = $value;
                    }
                    if($key == 'goods_num'){
                        $where['goods_num'] = $value;
                    }
                    if($key == 'name'){
                        $where2['name'] = $value;
                        $info = Storehouse::where($where2)->find();
                        $where['pg.storehouse_id'] = $info['id'];
                    }
//                    if($key == 'title'){
//                        $where['g.title'] = array('like','%'.$value.'%');
//                    }
//                    if($key == 'specs'){
//                        $where['g.specs'] = array('like','%'.$value.'%');
//                    }
//                    if($key == 'place_origin'){
//                        $where['g.place_origin'] = array('like','%'.$value.'%');
//                    }
//                    if($key == 'group_name'){
//                        $where['pg.group_name'] = array('like','%'.$value.'%');;
//                    }
//                    if($key == 'nickname'){
//                        $alist = Db::name('admin')->where(array('nickname'=>array('like','%'.$value.'%')))->select();
//                        $ids = [];
//                        foreach ($alist as $v){
//                            $ids[] = $v['id'];
//                        }
//                        if(empty($ids)){
//                            return  array("total" => 0, "rows" => []);
//                        }
//                        $where['a.id'] = array('in',$ids);
//                    }
//                    if($key == 'snick'){
//                        $alist = Db::name('supplier')->where(array('nickname'=>array('like','%'.$value.'%')))->select();
//                        $ids = [];
//                        foreach ($alist as $v){
//                            $ids[] = $v['id'];
//                        }
//                        if(empty($ids)){
//                            return  array("total" => 0, "rows" => []);
//                        }
//                        $where['g.supplier_id'] = array('in',$ids);
//                    }
//                    if($key == 'needtime'){
//                        $arr = explode(' - ', $value);
//                        $where['needtime'] = array('between time',$arr);
//                    }
//                    if($key == 'createtime'){
//                        $arr = explode(' - ', $value);
//                        $where['createtime'] = array('between time',$arr);
//                    }
                }
            }


            $sort = input('sort');
            $order = input('order');
            $offset = input('offset');
            $limit = input('limit');
            $list = Db::name('goods')
                ->field('pg.id,title,place_origin,unit,pg.status,sale_price,name,goods_num,type')
                ->alias('g')
                ->join('sales_goods pg','g.id = pg.goods_id')
                ->join('storehouse h','pg.storehouse_id = h.id')
                ->where($where)
//                ->where(array('g.id'=>$ids,'pg.status'=>array('>',1)))
                ->order('pg.id', $order)
                ->limit($offset, $limit)
                ->select();

            $mgoods = new smodel;
            $states = $mgoods->goods_status();
            $typess = $mgoods->goods_type();
            foreach ($list as $k=>$v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $states[$v['status']];
                $list[$k]['ytype'] = $v['type'];
                $list[$k]['type'] = $typess[$v['type']];
            }

            $total = Db::name('goods')
                ->alias('g')
                ->join('sales_goods pg','g.id = pg.goods_id')
                ->where($where)
                ->count();

            return  array(
                'rows'=>$list,
                'total'=>$total,
            );
        }

        return $this->view->fetch();
    }
    //报表
    public function report(){
        return $this->view->fetch();
    }
    public function import()
    {
        $filelink = request()->file('file');
        $info = $filelink->move(ROOT_PATH.'/public/'.DS.'uploads/fujian');
        //获取文件名
        $file = ROOT_PATH.'public'.DS.'uploads/fujian'.DS.$info->getsaveName();
            /* 转码 */
            $file = iconv("utf-8", "gb2312", $file);

            if (empty($file) OR !file_exists($file)) {
                throw new \Exception('文件不存在!');
            }

            /** @var Xlsx $objRead */
            $objRead = IOFactory::createReader('Xlsx');

            if (!$objRead->canRead($file)) {
                /** @var Xls $objRead */
                $objRead = IOFactory::createReader('Xls');

                if (!$objRead->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);
            /* 建立excel对象 */
            $obj = $objRead->load($file);
            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet(0)->toArray();
            unset($currSheet[0]);
            $gdata = [];

            foreach ($currSheet as $v){
                $brand = new Brands();
                $brow = $brand->where(array('name'=>$v[1]))->find();
                $cate = new Cate();
                $crow = $cate->where(array('name'=>$v[14]))->find();
                if($brow && $crow){

                    $gdata[] = array(
                        'title'=>$v[0],
                        'cate_id'=>$crow['id'],
                        'place_origin'=>$v[1],
                        'unit'=>$v[3],
                        'createtime'=>time(),
                        'supplier_id'=>$brow['supplier_id'],
                        'specs'=>$v[2],
                        'brands_id'=>$brow['id'],
                    );

                }
            }
            foreach ($gdata as $v){
                $cnumber = $cate->catenumber($v['cate_id']);
                $supplier = new Supplier();
                $sinfo = $supplier->find($v['supplier_id']);
                $brand = new Brands();
                $binfo = $brand->find($v['brands_id']);
                if(empty($binfo) || empty($sinfo) || $binfo['supplier_id'] != $sinfo['id']){
                    $this->error('数据异常');
                }
                $number = $cnumber.getnumber($sinfo['id']).$binfo['number'];
                $data = $v;
                $num = $this->model->where(array('supplier_id'=>$data['supplier_id'],'brands_id'=>$data['brands_id'],'cate_id'=>$data['cate_id']))->count();
                $data['number'] = $number.getnumbers($num);
                Db::name('goods')->insert($data);

            }
    }

    public function change($ids){
        $row = $this->model->find($ids);
        if($row){
            if($row['status'] == 'normal'){
                $data = array('status'=>'hidden');
            }
            if($row['status'] == 'hidden'){
                $data = array('status'=>'normal');
            }
            $res = $this->model->save($data,array('id'=>$ids));
            if($res){
                $this->success('操作成功');
            }
        }
        $this->error('操作失败');
    }

    //获取分类下数据
    public function getcate(){
        $cid = input('cid/d',0);
        if(empty($cid)){
            $this->error('非法数据');
        }
        $cate = new CateModel();
        $list = $cate->where(array('pid'=>$cid))->select();
        $this->success('','',$list);
    }


    public function stocklist($ids = null)
    {
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('数据异常');
        }
        if ($this->request->isAjax()) {
//            $list = Db::name('goods_house_stock')
            $datas = Db::name('storehouse')->select();
            $list = [];
            foreach ($datas as $v){
//                $house = new stock();
//                $stock =$house->getstock($ids,$v['id']);
                $hrow = Db::name('goods_house_stock')->where(array(
                    'storehouse_id'=>$v['id'],
                    'goods_id'=>$ids
                ))->find();
                $list[] = array(
                  'id'=>$v['id'],
                  'title'=>$row['title'],
                  'name'=>$v['name'],
                  'number'=>$row['number'],
                  'specs'=>$row['specs'],
                  'unit'=>$row['unit'],
                  'place_origin'=>$row['place_origin'],
                  'stock'=>isset($hrow['stock'])?$hrow['stock']:0,
                  'weighting_cost'=>isset($hrow['weighting_cost'])?$hrow['weighting_cost']:0,
                  'balance'=>isset($hrow['balance'])?$hrow['balance']:0,
                );
            }

            $stock = 0;
            foreach ($list as $v) {
                $stock += $v['stock'];
            }
            return array(
                'rows' => $list,
                'total' => count($list),
                'stock' => $stock,
            );
        }
        return $this->view->fetch();
    }
    public function updatestock($ids= null){
        $hid = input('hid/d',0);
        $stock = trim(input('pass/d',0));
        $balance = trim(input('balance',0));//现在是成本均价

        $row = Db::name('goods_house_stock')->where(array('goods_id'=>$ids,'storehouse_id'=>$hid))->find();
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        if(empty($row)){
            $before_num = 0;
            $before_balance = 0;
            $res = Db::name('goods_house_stock')->insert(array(
               'goods_id'=>$ids,
               'storehouse_id'=>$hid,
               'stock'=>$stock,
               'weighting_cost'=>$balance,
               'balance'=>bcmul($balance,$stock,4),
            ));
        }else{
            $before_num = $row['stock'];
            $before_balance = $row['balance'];
            $res = Db::name('goods_house_stock')->where(array('goods_id'=>$ids,'storehouse_id'=>$hid))->update(array(
                'stock'=>$stock,
                'weighting_cost'=>$balance,
                'balance'=>bcmul($balance,$stock,4),
            ));
        }
        if($res){
            Db::name('goods_edit_stock')->insert(array(
               'storehouse_id'=>$hid,
               'goods_id'=>$ids,
               'createtime'=>time(),
               'before_num'=>$before_num,
               'before_balance'=>$before_balance,
               'now_num'=>$stock,
               'now_balance'=>bcmul($balance,$stock,4),
               'admin_id'=>session('admin')['id'],
               'group_id'=>$group['group_id'],
               'company'=>$group['name'],
               'operator'=>session('admin')['nickname'],
            ));
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }




    /*
     * 商品库存状况
     */
    public function stockgoods(){
        $where=[];
        if(session('admin')['storehouse_id'] >0){
            $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
            $where['s.storehouse_id'] = $hrow['id'];
        }else{
            $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
            $where['s.storehouse_id'] = $hrow['id'];
        }
        if ($this->request->isAjax())
        {
            $filter = input('filter');
            $filter = json_decode($filter,true);
            $search = input('search');
            if(!empty($search)){
                $where['g.title|g.number'] = array('like','%'.trim($search).'%');
            }
            if(!empty($filter)){
                foreach ($filter as $key => $value){
                    if($key == 'title'){
                        $where['g.title'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'number'){
                        $where['g.number'] = trim($value);
                    }
                    if($key == 'id'){
                        $where['g.id'] = trim($value);
                    }
                }
            }

            $page = input('offset/d',0);
            $pagesize = input('limit/d',10000);
            $list = Db::name('goods')
                ->alias('g')
                ->field('g.id,new_cost,cumulative,weighting_cost,balance,stock,title,g.number,specs,place_origin,unit,name')
                ->where($where)
                ->join('goods_house_stock s','g.id = s.goods_id')
                ->join('supplier_brands b','g.brands_id = b.id','LEFT')
                ->limit($page,$pagesize)
                ->select();
            $numbers = [];
            foreach ($list as $v){
                $numbers[] = $v['number'];
            }
            $stocks = $this->getprice(implode(',',$numbers),$hrow['code']);
            foreach ($list as &$v){
                foreach ($stocks as $val){
                    if($v['number'] == $val['spec_num']){
                        $v['store_count'] = $val['store_count'];
                    }
                }
            }


            $total = Db::name('goods')
                ->alias('g')
                ->where($where)
                ->join('goods_house_stock s','g.id = s.goods_id')
                ->join('supplier_brands b','g.brands_id = b.id','LEFT')
                ->count();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign('hrow',$hrow);
        return $this->view->fetch();
    }
    /*
    * 商品库存状况
    */
    protected function getprice($numbers,$code){

        if(isset($json['code']) && $json['code'] == 9){
            return [];
        }
        if(!empty($json) && $json['code']  == 1){
            return $json['data'];
        }else{
            return [];
        }
    }

    public function editlog(){
        if ($this->request->isAjax())
        {
            $where = [];
            $filter = input('filter');
            $filter = json_decode($filter,true);
            $search = input('search');
            if(!empty($search)){
                $where['g.title|g.number'] = array('like','%'.trim($search).'%');
            }
            if(!empty($filter)){
                foreach ($filter as $key => $value){
                    if($key == 'title'){
                        $where['g.title'] = array('like','%'.trim($value).'%');
                    }
                    if($key == 'number'){
                        $where['g.number'] = trim($value);
                    }
                    if($key == 'createtime'){
                        $arr = explode(' - ', $value);
                        $where['e.createtime'] = array('between time',$arr);
                    }
                }
            }

            $page = input('offset/d',0);
            $pagesize = input('limit/d',10000);
            $list = Db::name('goods_edit_stock')
                ->alias('e')
                ->where($where)
                ->field('e.*,g.title,g.specs,g.number,h.name')
                ->join('goods g','e.goods_id = g.id','LEFT')
                ->join('storehouse h','e.storehouse_id = h.id','LEFT')
                ->order('id','desc')
                ->limit($page,$pagesize)
                ->select();


            $total = Db::name('goods_edit_stock')
                ->alias('e')
                ->where($where)
                ->join('goods g','e.goods_id = g.id','LEFT')
                ->count();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function seachbill(){
        $storehouse_id = input('storehouse_id/d',0);
        $goods_id = input('goods_id/d',0);
        $this->assign('goods_id',$goods_id);
        $this->assign('storehouse_id',$storehouse_id);
        return $this->view->fetch();
    }
    public function dilllist(){
        if ($this->request->isAjax()) {
            $starttime = strtotime(input('starttime'));
            $endtime = strtotime(input('endtime'));
            $goods_id = input('goods_id');
            $storehouse_id = input('storehouse_id');
            $admin_id = input('admin_id');
            $where = [];
            $where['createtime'] = array('between time', [$starttime, $endtime]);
            $where['storehouse_id'] = $storehouse_id;
            $where['goods_id'] = $goods_id;
            if (!empty($admin_id)) {
                $where['admin_id'] = $admin_id;
            }
            $houses = Db::name('storehouse')->select();
            $where['goods_id'] = $goods_id;
//            $where['is_cancel'] = 0;
            $page = input('offset/d',0);
            $plimit = input('limit/d',0);
            $list = Db::name('goods_stock_log')
                ->limit($page,$plimit)
                ->where($where)
                ->select();
            $sales_ids = [];
            $purchase_ids = [];
            foreach ($list as $k=>$v){
                foreach ($houses as $val){
                    if($v['storehouse_id'] == $val['id']){
                        $list[$k]['hname'] = $val['name'];
                    }
                }
                if($v['controller'] =='sales/checkout'){
                    $sales_ids[] = $v['type_id'];
                }else if ($v['controller'] == 'purchase/enter'){
                    $purchase_ids[] = $v['type_id'];
                }else{
                    $list[$k]['billing'] = '';
                    $list[$k]['nickname'] = '';
                }
            }


            if(!empty($sales_ids)){
                $sales =Db::name('sales_checkout')
                    ->field('cs.nickname,s.operator,c.id')
                    ->alias('c')
                    ->join('sales_slip s','c.sales_slip_id = s.id')
                    ->join('customer cs','c.customer_id = cs.id')
                    ->where(array('c.id'=>array('in',$sales_ids)))
                    ->select();
                foreach ($sales as $val){
                    foreach ($list as $k=> $v){
                        if($v['controller'] =='sales/checkout' && $val['id'] == $v['type_id']){
                            $list[$k]['billing'] = $val['operator'];
                            $list[$k]['nickname'] = $val['nickname'];
                        }
                    }
                }
            }
            if(!empty($purchase_ids)){
                $sales =Db::name('purchase_enter')
                    ->field('s.nickname,o.operator,e.id')
                    ->alias('e')
                    ->join('purchase_order o','e.purchase_order_id = o.id')
                    ->join('supplier s','e.supplier_id = s.id')
                    ->where(array('e.id'=>array('in',$purchase_ids)))
                    ->select();
                foreach ($sales as $val){
                    foreach ($list as $k=> $v){
                        if($v['controller'] =='purchase/enter' && $val['id'] == $v['type_id']){
                            $list[$k]['billing'] = $val['operator'];
                            $list[$k]['nickname'] = $val['nickname'];
                        }
                    }
                }
            }

            $total = Db::name('goods_stock_log')
                ->where($where)
                ->count();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    public function editstatus(){
        $ids = input('ids/d',0);
        $version = input('version/d',0);
        $res = Db::name('goods')->where(array('id'=>$ids))->update(array('sync_status'=>$version));
        if($res){
            $this->success('修改成功');
        }else{
            $this->success('修改失败');
        }
    }
    public function purchasegoods(){
        $where=[];
        if(session('admin')['storehouse_id'] >0){
            $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
            $where['s.storehouse_id'] = $hrow['id'];
        }else{
            $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
            $where['s.storehouse_id'] = $hrow['id'];
        }
        $this->assign('hrow',$hrow);
        return $this->view->fetch();
    }

    public function compose($ids = null){
        if ($this->request->isAjax()) {
            Db::startTrans();
            try {
                $data = input();
                Db::name("goods_material")->where(array('goods_id'=>$ids))->delete();
                if (!empty($data['cost'])){
                    $vdata = [];
                    foreach ($data['cost'] as $k=>$v){
                        $vdata[] = [
                            'goods_id'=>$ids,
                            'material_id'=>$v['goods_id'],
                            'material_num'=>$v['goods_num'],
                            'createtime'=>time(),
                        ];
                    }
                    Db::name("goods_material")->insertAll($vdata);
                }
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'设置成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
        $row = $this->model->find($ids);
        $materGoods = Db::name('goods_material')
            ->field("m.*,g.*,b.name")
            ->alias('m')
            ->join('goods g','m.material_id = g.id')
            ->join("supplier_brands b",'g.brands_id = b.id')
            ->where(array('m.goods_id'=>$ids))
            ->select();

        $allcost = 0;
        foreach ($materGoods as $val){
            $allcost+=bcmul($val['new_cost_price'],$val['material_num'],2);
            bcadd($allcost,0,2);
        }
        $this->assign('allcost',$allcost);
        $this->assign('materGoods',$materGoods);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function seach(){
        $house_id = input('house_id/d',0);

        $this->assign('house_id',$house_id);
        return $this->view->fetch();
    }
    public function getgood($ids = null){
        $house_id = input('house_id/d',0);
        $hrow = Db::name('storehouse')->where(array('id'=>$house_id))->find();
        $good = new \app\common\model\goods\Goods();
        $ginfo = $good->where(array('id'=>$ids))->find();
        if(empty($ginfo)){
            $this->error('无商品');
        }

        if(!empty($json) && $json['code']  == 1){
            $ginfo['price'] = $json['data'];
        }else{
            $ginfo['price'] = 0;
        }
        $GoodsHouseStock = new GoodsHouseStock;

        if (empty($house_id)){
            $house = Db::name("storehouse")->find();
            if (empty($house)){
                $this->error('请先设置仓库');
            }
            $house_id = $house['id'];
            $stock = Db::name("goods_house_stock")->where(array('goods_id'=>$ids,'storehouse_id'=>$house_id))->find();
            $ginfo['stock'] = empty($stock['stock'])?0:$stock['stock'];
            $ginfo['new_cost_price'] = empty($stock['weighting_cost'])?0:$stock['weighting_cost'];
        }

        $ginfo['xstock'] = $GoodsHouseStock->getfictstock($ginfo['id'],$house_id);
//        $ginfo['stock'] = $GoodsHouseStock->getstock($ginfo['id'],$house_id);
        return $ginfo;
    }
}
